import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


def draw_pie_chart(window):
    window.withdraw()  # 隐藏当前窗口
    pie_window = tk.Toplevel() # 创建一个新的Toplevel窗口来显示饼状图
    pie_window.title("绘制饼状图")
    pie_window.geometry("400x500")

    # 用户输入数据
    tk.Label(pie_window, text="输入数据，用逗号分隔（如：30,20,10）:").pack()
    data_entry = tk.Entry(pie_window)
    data_entry.pack()

    def plot_pie_chart():
        # 获取用户输入的数据
        data_str = data_entry.get()
        data_list = [int(x) for x in data_str.split(',')]
        labels = [f"部分{i+1}" for i in range(len(data_list))]

        # 创建一个Figure对象
        fig = Figure(figsize=(5, 4), dpi=100)
        ax = fig.add_subplot(111)

        # 绘制饼状图
        ax.pie(data_list, labels=labels, autopct='%1.1f%%', startangle=140)

        # 确保饼状图是圆形的
        ax.axis('equal')

        # 将Figure对象转换为Tkinter画布
        canvas = FigureCanvasTkAgg(fig, master=pie_window)
        canvas.draw()
        canvas.get_tk_widget().pack()

        # 隐藏输入部分
        data_entry.pack_forget()

    # 添加绘制饼状图按钮
    plot_button = tk.Button(pie_window, text="绘制饼状图", command=plot_pie_chart)
    plot_button.pack()

    # 添加返回按钮，返回到原始画图窗口
    return_button = tk.Button(pie_window, text="返回", command=lambda: [pie_window.destroy(), window.deiconify()])
    return_button.pack()